//
//  YWVideoView3.m
//  videoTest3
//
//  Created by jun peng on 2022/7/14.
//

#import "YWVideoView3.h"
#import <TXLiteAVSDK_Player/TXLiteAVSDK.h>

@interface YWVideoView3 ()
@property (nonatomic, assign) BOOL mute;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *rateLabel;

@property(nonatomic,copy)NSString *urlString;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (weak, nonatomic) IBOutlet UIButton *loadingView;
@property (weak, nonatomic) IBOutlet UIView *videoView;

@property (weak, nonatomic) IBOutlet UIView *videoTopFunctionView;

@property (weak, nonatomic) IBOutlet UIView *videoBottomFunctionView;

- (IBAction)bigScaleBtnClick:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UIButton *playOrPauseBtn;
- (IBAction)playOrPauseBtnClick:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
- (IBAction)sliderValueChange;
- (IBAction)touchDownSlider;
- (IBAction)touchUpInsideSlider;

//播放器是否正在播放 （这个是暂停播放也算是YES的\暂停播放也叫正在播放）
@property (nonatomic, assign) BOOL isPlaying_containPause;

@property(nonatomic,weak)CAGradientLayer *gradientTopLayer;
@property(nonatomic,weak)CAGradientLayer *gradientBottomLayer;

- (IBAction)snapClick:(UIButton *)sender;

@property (nonatomic,strong)NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIButton *snapBtn;

@property(nonatomic,assign)CGFloat sliderCurrentTime;

@end

@implementation YWVideoView3

-(BOOL)isPlaying_containPause{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
  
    if (playerManager.currentVideoMessageModel.player != nil) {
        return YES;
    }
    else{
        return NO;
        
    }
}

//创建videoPlayView
+ (instancetype)videoView{
    
    return [[[NSBundle mainBundle] loadNibNamed:@"YWVideoView3" owner:nil options:nil] firstObject];
}


-(void)awakeFromNib{
    [super awakeFromNib];
    
    //单击手势控制toolView出现
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self addGestureRecognizer:tap];
    
    [self setupUI];
    
    
    
    CAGradientLayer *gradientTopLayer = [CAGradientLayer layer];
    self.gradientTopLayer = gradientTopLayer;
    gradientTopLayer.colors = @[(__bridge id)YWColorRGBA(0, 0, 0, 0.6).CGColor, (__bridge id)YWColorRGBA(0, 0, 0, 0.0).CGColor];
    gradientTopLayer.locations = @[@0,@1.0];
    gradientTopLayer.startPoint = CGPointMake(0, 0);
    gradientTopLayer.endPoint = CGPointMake(0, 1.0);
       [self.videoTopFunctionView.layer addSublayer:gradientTopLayer];
    [self.videoTopFunctionView.layer insertSublayer:gradientTopLayer atIndex:0];
    
    CAGradientLayer *gradientBottomLayer = [CAGradientLayer layer];
    self.gradientBottomLayer = gradientBottomLayer;
    gradientBottomLayer.colors = @[(__bridge id)YWColorRGBA(0, 0, 0, 0.6).CGColor, (__bridge id)YWColorRGBA(0, 0, 0, 0.0).CGColor];
    gradientBottomLayer.locations =  @[@0,@1.0];
    gradientBottomLayer.startPoint = CGPointMake(0, 1.0);
    gradientBottomLayer.endPoint = CGPointMake(0, 0.0);
    [self.videoBottomFunctionView.layer addSublayer:gradientBottomLayer];
    [self.videoBottomFunctionView.layer insertSublayer:gradientBottomLayer atIndex:0];
    
    UILongPressGestureRecognizer *gesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressGestures:)];
    [self addGestureRecognizer:gesture];
    
    
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:pan];
    
    
    
    self.rateLabel.alpha = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground) name:YWEnterBackgroundNote object:nil];
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self removeTimer];
}

-(void)enterBackground{
    
    [self pausePlay];
    self.playOrPauseBtn.selected = NO;
    
}
- (void)handleLongPressGestures:(UILongPressGestureRecognizer *)gesture{
    
       switch (gesture.state) {
           case UIGestureRecognizerStateBegan:
           {
               
               if (!self.isPlaying) {
                   [self continuePlay];
               }
               
               YWVideoPlayerManager *manager = [YWVideoPlayerManager sharevideoPlayerManager];
               [manager setRate:3];
               
               [self removeTimer];
               
               [self changeRateLabelAlpha];
               
               //添加定时器
               [self addTimer];
               
           }
               break;
           case UIGestureRecognizerStateChanged:
           {
               
           }
               break;
           case UIGestureRecognizerStateEnded:
           {
               
                   YWVideoPlayerManager *manager = [YWVideoPlayerManager sharevideoPlayerManager];
                   [manager setRate:1];
           
               
               [self removeTimer];
           }
               break;
               
           default:
               break;
       }
       
}

-(void)pan:(UIPanGestureRecognizer *)pan{
 
    CGPoint transP = [pan translationInView:self];
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {
            [self pausePlay];
            
            YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
            
            NSTimeInterval currentTime = playerManager.currentVideoMessageModel.costTime;
            
            self.sliderCurrentTime = currentTime;
            
            [UIView animateWithDuration:0.5 animations:^{
                self.videoTopFunctionView.alpha = 1;
                self.videoBottomFunctionView.alpha = 1;
                
            }];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            
            YWLog(@"transP.x:%f",transP.x);
            
            YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
            
            if (self.sliderCurrentTime > playerManager.currentVideoMessageModel.totalTime) {
                
                return;
                
            }   
            
            if (self.sliderCurrentTime <=0 ){
                
                self.currentTimeLabel.text = @"00:00";
                
                return;
            }
            
            
            self.sliderCurrentTime+=transP.x;
            
            self.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:self.sliderCurrentTime];
            
            self.progressSlider.value = self.sliderCurrentTime / playerManager.currentVideoMessageModel.totalTime;
            
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
            
            // 更新视频进度
            [playerManager seekToTime:self.sliderCurrentTime];
            
            [self continuePlay];
            
            [UIView animateWithDuration:0.5 animations:^{
                self.videoTopFunctionView.alpha = 0;
                self.videoBottomFunctionView.alpha = 0;
                
            }];
        }
            break;
            
        default:
            break;
    }
    
    //复位.
    [pan setTranslation:CGPointZero inView:self];
    
}

//添加定时器
-(void)addTimer{
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(changeRateLabelAlpha) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

//移除定时器
-(void)removeTimer{
    
    [self.timer invalidate];
    
    self.timer = nil;
    
}

-(void)changeRateLabelAlpha{
    [UIView animateWithDuration:0.7 animations:^{
        self.rateLabel.alpha = 1;
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.7 animations:^{
            self.rateLabel.alpha = 0;
        }completion:^(BOOL finished) {
            
        }];
    }];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    self.gradientTopLayer.frame = CGRectMake(0, 0, Wi, self.videoTopFunctionView.height);
    self.gradientBottomLayer.frame = CGRectMake(0, 0, Wi, self.videoBottomFunctionView.height);
}

-(void)setupUI{
    
    self.backgroundColor = [UIColor blackColor];
    
    
    //先默认隐藏
    self.loadingView.hidden = YES;
    self.videoTopFunctionView.alpha = 0;
    self.videoBottomFunctionView.alpha = 0;
    
    //添加loading动画
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 0.9;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    rotationAnimation.removedOnCompletion = NO;//这个属性才会重新出现界面时不会停止动画
    [self.loadingView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
   
    
    // 设置进度条的内容
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"进度条原点3"] forState:UIControlStateNormal];
    [self.progressSlider setMaximumTrackImage:[UIImage imageNamed:@"MaximumTrackImage"] forState:UIControlStateNormal];
    [self.progressSlider setMinimumTrackImage:[UIImage imageNamed:@"MinimumTrackImage"] forState:UIControlStateNormal];
    
    
    // 2、设置按钮的状态
    self.playOrPauseBtn.selected = NO;
    
    // 3、设置slider
    self.progressSlider.value = 0;
    
    // 4、设置两个时间label
    self.currentTimeLabel.text = @"00:00";
    
    self.totalTimeLabel.text = @"00:00";
    
    self.snapBtn.layer.cornerRadius = 5;
    self.snapBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.snapBtn.layer.borderWidth = 1;
    
}


//单击
- (void)tapAction:(UITapGestureRecognizer *)sender {

    
    CGFloat alpha = 1 - self.videoTopFunctionView.alpha;
    
    YWLog(@"alpha:%f",alpha);
    [UIView animateWithDuration:0.5 animations:^{
        self.videoTopFunctionView.alpha = alpha;
        self.videoBottomFunctionView.alpha = alpha;
        
        
        
    }];
    
    
    if ([self.delegate respondsToSelector:@selector(videoViewDidTap:)]) {
        [self.delegate videoViewDidTap:self];
    }
    
}

//开始
-(void)startPlayWithUrl:(NSString *)urlString withMute:(BOOL)mute{
    
    self.playOrPauseBtn.selected = YES;
    
    self.videoTopFunctionView.alpha = 0;
    self.videoBottomFunctionView.alpha = 0;
    
    self.urlString = urlString;
    
    MJWeakSelf
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
  
      [playerManager startPlayWithUrl:urlString view:self.videoView complication:^{
          
          //重设是否要静音
//          weakSelf.mute = weakSelf.mute;
          
          //这里用在朋友圈列表、默认就是静音
          //是否静音这里应该是YES
          
          //因为列表VC和小视频详情VC都共用这个videoView、所以mute由外界提供
          weakSelf.mute = mute;
          
          if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidStartPlay:)]) {
              [weakSelf.delegate videoViewDidStartPlay:weakSelf];
          }
  
      } startPlay:^{
          
          weakSelf.loadingView.hidden = YES;
          
         
  
      } progress:^(float progress, float duration, float playable) {
  
          weakSelf.loadingView.hidden = YES;
          if (weakSelf.isPlaying) {
              weakSelf.playOrPauseBtn.selected = YES;
          }
          else{
              
              weakSelf.playOrPauseBtn.selected = NO;
              
          }
          
          weakSelf.progressSlider.value = progress / duration;
          
          weakSelf.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:duration];
          
          weakSelf.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:progress];
          
          
      } end:^{
  
      } loading:^{
          weakSelf.loadingView.hidden = NO;
          
      }];
    
}


-(void)continuePlayWithAnthorViewWithUrl:(NSString *)urlString WithMute:(BOOL)mute{
   
    self.playOrPauseBtn.selected = YES;
    
    self.videoTopFunctionView.alpha = 0;
    self.videoBottomFunctionView.alpha = 0;
    
    self.urlString = urlString;
    
    MJWeakSelf
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    //继续播放
    [self continuePlay];

    [playerManager continuePlayWithAnthorView:self.videoView complication:^{
        
        weakSelf.mute = mute;
        
        if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidStartPlay:)]) {
            [weakSelf.delegate videoViewDidStartPlay:weakSelf];
        }
        
    } startPlay:^{
        weakSelf.loadingView.hidden = YES;
       
        
    } progress:^(float progress, float duration, float playable) {
        weakSelf.loadingView.hidden = YES;
        if (weakSelf.isPlaying) {
            weakSelf.playOrPauseBtn.selected = YES;
        }
        else{
            
            weakSelf.playOrPauseBtn.selected = NO;
            
        }
        
        weakSelf.progressSlider.value = progress / duration;
        
        weakSelf.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:duration];
        
        weakSelf.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:progress];
        
    } end:^{
        
    } loading:^{
        weakSelf.loadingView.hidden = NO;
    }];
    
  
    
}

//暂停
-(void)stopPlay{
    
    MJWeakSelf
 
        YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
        [playerManager stopPlayWithComplication:^{
            if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidSotpPlay:)]) {
                [weakSelf.delegate videoViewDidSotpPlay:weakSelf];
            }
        }];
    
    self.playOrPauseBtn.selected = NO;
}

//暂停
-(void)pausePlay{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager pausePlayWithComplication:^{
        
    }];
    
    self.playOrPauseBtn.selected = NO;
    
    
}

//继续
-(void)continuePlay{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager continuePlayWithComplication:^{
        
    }];
    
    self.playOrPauseBtn.selected = YES;
}



-(void)setMute:(BOOL)mute{
    _mute = mute;
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    [playerManager setMute:mute];
    
}

-(BOOL)isPlaying{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    return playerManager.currentVideoMessageModel.isPlaying;
}


- (void)snapshot:(void (^)(UIImage *))snapshotCompletionBlock{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    [playerManager snapshot:^(UIImage * _Nonnull image) {
        if (snapshotCompletionBlock) {
            snapshotCompletionBlock(image);
        }
    }];
    
}


- (IBAction)sliderValueChange{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    // 更新时间label数据
    NSTimeInterval currentTime = playerManager.currentVideoMessageModel.totalTime * self.progressSlider.value;
    
    NSTimeInterval totalTime = playerManager.currentVideoMessageModel.totalTime;
    
    
    self.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:currentTime];
    
    self.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:totalTime];
    
    // 更新视频进度
    [playerManager seekToTime:currentTime];
}
     
- (IBAction)touchDownSlider{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager pausePlayWithComplication:^{
        
    }];
    
}
- (IBAction)touchUpInsideSlider{
    [self continuePlay];
    
    //怕它不灵敏、再来一次调用继续
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self continuePlay];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self continuePlay];
    });
    
    YWLog(@"aaa---touchUpInsideSlider");
    
    
}

- (IBAction)playOrPauseBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        [self continuePlay];
    }
    else{
        [self pausePlay];
    }
}

- (IBAction)bigScaleBtnClick:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(videoView:didClickBigScaleBtn:)]) {
        [self.delegate videoView:self didClickBigScaleBtn:sender];
    }
    
}

-(void)setStatus:(YWKLineCheatsVideoListDataStatus *)status{
    
    _status = status;
    
    if (![status.PicUrl isKindOfClass:[NSNull class]] && status.PicUrl != nil) {
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:status.PicUrl] placeholderImage:[UIImage imageNamed:@""]];
        
    }
    else{
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""]];
        
    }
    
    self.titleLabel.text = status.Title;
    
    
    
}

- (IBAction)snapClick:(UIButton *)sender {
    
    [self snapshot:^(UIImage * _Nonnull image) {
        
        if (image == nil) {
            return;
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }];
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error != nil) {
        [MBProgressHUD showError:@"保存失败" toView:[UIApplication sharedApplication].keyWindow];
    }
    else{
        [MBProgressHUD showSuccess:@"保存成功" toView:[UIApplication sharedApplication].keyWindow];
    }
}
    

@end
